package com.hhs.storage.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hhs.storage.bean.*;
import com.hhs.storage.service.AttachmentDirService;
import com.hhs.storage.service.AttachmentListService;
import com.hhs.storage.service.BaseRoleService;
import com.hhs.storage.service.BaseUserService;
import com.hhs.storage.util.DateEasy;
import com.hhs.storage.util.StringUtil;
import com.hhs.storage.util.SysUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author chx
 * @since 2024-06-27
 */
@RestController
@RequestMapping("/attachmentDir")
public class AttachmentDirController {
    @Resource
    private AttachmentDirService attachmentDirService;
    @Resource
    private AttachmentListService attachmentListService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private BaseRoleService baseRoleService;
    @Resource
    private BaseUserService baseUserService;
    //增加方法
    @RequestMapping(value = "edit")
    public Object edit(AttachmentDir attachmentDir) {
        if (StringUtil.iszNull(attachmentDir.getId())) {
            attachmentDir.setCreateTime(new DateEasy().toLocalDateTime());
            attachmentDir.setUserId(SysUtil.getLoginUserId(request));
        }
        attachmentDirService.saveOrUpdate(attachmentDir);
        return ResponseInfo.success();
    }

    //增加方法
    @RequestMapping(value = "table")
    public Object table(InputParam inputParam) {
        QueryWrapper<AttachmentDir> qw = new QueryWrapper<>();
        if (inputParam.getType() != null) {
            //我的文件夹
            if (inputParam.getType() == 1) {
                qw.eq("user_id", SysUtil.getLoginUserId(request)).or().isNull("user_id");
            }
            //它人的文件夹，所有者不是我且我有权限
            if (inputParam.getType() == 2) {
                qw.ne("user_id", SysUtil.getLoginUserId(request)).or().isNull("user_id");
            }
        }
        qw.orderByAsc("sort_id");
        List<AttachmentDir> list = attachmentDirService.list(qw);
        List<AttachmentDir> realist = new ArrayList<>();
        for (AttachmentDir ad :
                list) {
            JSONObject map = (JSONObject) JSONObject.parse(ad.getPermission());
            if (hasDisPermission(ad, map, null)) {
                BaseUser byId = baseUserService.getById(ad.getUserId());
                if(byId!=null)
                ad.setUserName(byId.getName());
                realist.add(ad);
            }
        }
        return ResponseInfo.success(realist);
    }

    /**
     * 有权限
     *
     * @param map
     * @return
     */
    private boolean hasDisPermission(AttachmentDir ad, JSONObject map, Integer type) {
        //登录者的Id
        String loginId = SysUtil.getLoginUserId(request);
        //自己的和总目录的都要返回,默认者
        if (loginId.equals("2") || loginId.equals(ad.getUserId())|| loginId.equals("21")) {
            return true;
        }
        //是总目录时
        if (ad.getUserId() == null) {
            if (type == null) {//列表权限
                return true;
            }
            if (type == 0 || type == 1) {
                return false;
            }
        }
        if (map == null) {
            return false;
        }
        //用户
        List<JSONObject> permissionData = (List) map.get("permissionData");
        List<BaseRole> roles = baseRoleService.getByUserId(loginId);
        List<String> rids = roles.stream().map(itemm -> itemm.getId()).collect(Collectors.toList());
        for (JSONObject item :
                permissionData) {
            //用户有没有权限
            if (((Integer) item.get("type")) == 0) {
                String userId = (String) item.get("id");
                if (loginId.equals(userId)) {
                    List<Integer> checkList = (List) item.get("checkList");
                    if (checkList == null) {
                        return false;
                    } else {
                        boolean f = false;
                        if (type == null) {
                            f = checkList.contains(0) || checkList.contains(1) || checkList.contains(2);
                        } else {
                            f = checkList.contains(type);
                        }
                        return f;
                    }
                }
            }

            if (((Integer) item.get("type")) == 1) {//角色有没有权限
                String roleId = (String) item.get("id");
                if (rids.contains(roleId)) {
                    List<Integer> checkList = (List) item.get("checkList");
                    if (checkList == null) {
                        return false;
                    } else {
                        boolean f = false;
                        if (type == null) {
                            f = checkList.contains(0) || checkList.contains(1) || checkList.contains(2);
                        } else {
                            f = checkList.contains(type);
                        }
                        return f;
                    }
                }
            }
        }
        return false;
    }

    //删除方法
    @RequestMapping(value = "dele")
    public Object dele(InputParam inputParam) {
        if (StringUtil.iszNull(inputParam.getId())) {
            return ResponseInfo.error("参数错误");
        }
        QueryWrapper<AttachmentDir> qw = new QueryWrapper();
        qw.eq("pid", inputParam.getId());
        int count = attachmentDirService.count(qw);
        if (count > 0) {
            return ResponseInfo.error("有子文件夹，后台不允许删除");
        }
        QueryWrapper<AttachmentList> qww = new QueryWrapper();
        qww.eq("target_id", inputParam.getId());
        int count2 = attachmentListService.count(qww);
        if (count2 > 0) {
            return ResponseInfo.error("文件夹下有文件，请删除后再继续");
        }
        AttachmentDir byId = attachmentDirService.getById(inputParam.getId());
        if (hasDisPermission(byId, (JSONObject) JSONObject.parse(byId.getPermission()), 1)) {
            attachmentDirService.removeById(inputParam.getId());
            return ResponseInfo.success();
        } else {
            return ResponseInfo.error("您没有删除权限");
        }
    }

    //修改方法
    @RequestMapping(value = "getById")
    public Object getById(InputParam inputParam) {
        if (StringUtil.iszNull(inputParam.getId())) {
            return ResponseInfo.error("参数错误");
        }
        AttachmentDir byId = attachmentDirService.getById(inputParam.getId());
        if (hasDisPermission(byId, (JSONObject) JSONObject.parse(byId.getPermission()), 0)) {
            return ResponseInfo.success(byId);
        } else {
            return ResponseInfo.error("您没有修改权限");
        }

    }
}

